<?php

(defined('BASEPATH')) OR exit('No direct script access allowed');

/**
 * PENGUIN FrameWork
 * @author hungtd <tdhungit@gmail.com> 0972014011
 * @copyright Tran Dinh Hung 2011
 * 
 * Add MY_Controller with ACL and ...
 * 
 * @package PenguinFW
 * @subpackage Controller
 * @version 1.0.0
 * 
 * @property CI_Loader $load
 * @property CI_Session $session
 * @property MY_Router $router
 * @property CI_Parser $parser
 * @property Layout $layout
 * 
 * @property CI_Input $input
 * @property CI_Form_validation $form_validation
 * @property CI_Table $table
 * 
 * @property CI_DB_active_record $db
 * @property CI_DB_forge $dbforge
 * 
 * @property CI_Email $email
 */
class MY_Controller extends CI_Controller
{
    // config query pagination
    protected $paginator = array('limit' => 20);
    
    // model name
    protected $model_name = '';
    
    // count all query
    protected $count_record;

    function __construct()
    {
        parent::__construct();
    }

    /**
     * Kiểm tra phân quyền trên từng trang
     * 
     * @param string $penguin_permission r:read, w:write, e:modify, p:publish, d:delete
     */
    public function PG_ACL($penguin_permission = 'r')
    {
        $is_permission = $this->check_PG_ACL($this->getUserRole(), $this->router->class, $penguin_permission);

        if ($is_permission == FALSE)
        {
            redirect('users/permission');
        }
    }

    /**
     * Kiểm tra quyền truy cập của user
     * Nếu không được phép truy cập redirect về trang thông báo
     * 
     * @param role id $role_id
     * @param int $resource_name controller name
     * @param string $penguin_permission r:read, w:write, e:modify, p:publish, d:delete
     * @return boolean
     */
    public function check_PG_ACL($role_id, $resource_name, $penguin_permission = 'r')
    {
        $this->load->library('acl');

        $is_permission = FALSE;

        $this->db->select('id');
        $resource = $this->db->get_where('module_resources', array('name' => $resource_name))->row();
        $resource_id = $resource->id;

        switch ($penguin_permission)
        {
            case 'r':
                $is_permission = $this->acl->is_read($role_id, $resource_id);
                break;
            case 'w':
                $is_permission = $this->acl->is_write($role_id, $resource_id);
                break;
            case 'e':
                $is_permission = $this->acl->is_modify($role_id, $resource_id);
                break;
            case 'p':
                $is_permission = $this->acl->is_publish($role_id, $resource_id);
                break;
            case 'd':
                $is_permission = $this->acl->is_delete($role_id, $resource_id);
                break;
            default:
                break;
        }

        return $is_permission;
    }

    /**
     * Lấy role của user
     * Nếu user chưa đăng nhập thì role là guest
     * 
     * @return int role_id
     */
    public function getUserRole()
    {
        if ($this->session->userdata('user_id') > 0)
            return $this->session->userdata('user_user_role_id');
        else
            return ConstUserRole::guest;
    }

    /**
     * get Custom field show on page
     * 
     * @param int $user_id user id 
     * @param int $cfn_id custom field name id
     * @param boolean $is_main
     * @return array fields
     */
    public function getCustomField($user_id, $cfn_id = 0, $resource_name = '', $is_main = TRUE)
    {
        $resource_name = ($resource_name) ? $resource_name : $this->router->class;
        
        $resource_id = $this->getResourceID($resource_name, $is_main);

        if ($cfn_id == 0)
        {
            $conditions = array(
                'custom_field_names.resource_id' => $resource_id,
                'custom_field_names.name' => ConstCustomField::defaultName,
                'custom_field_names.user_id' => $user_id
            );
        } else
        {
            $conditions = array(
                'custom_field_names.resource_id' => $resource_id,
                'custom_field_names.id' => $cfn_id,
                'custom_field_names.user_id' => $user_id
            );
        }

        // get custom field for resource
        $this->db->select('module_fields.name, module_fields.field_type');
        $this->db->from('custom_fields');
        $this->db->join('custom_field_names', 'custom_fields.name_id = custom_field_names.id');
        $this->db->join('module_fields', 'custom_fields.field_id = module_fields.id');
        $this->db->where($conditions);

        $module_fields = $this->db->get();

        $fields = array();

        if ($module_fields->num_rows() > 0)
        {
            foreach ($module_fields->result() as $fieldObj)
            {
                $fields[$fieldObj->name] = $fieldObj->field_type;
            }
        }
        
        if (empty ($fields))
        {
            return false;
        }

        return $fields;
    }

    /**
     * get all custom field name
     * 
     * @param string $resource_name
     * @param boolean $is_main
     * @return array
     */
    public function getCustomFieldName($resource_name = '', $is_main = TRUE)
    {
        $resource_name = ($resource_name) ? $resource_name : $this->router->class;
        
        $resource_id = $this->getResourceID($resource_name, $is_main);
        
        $this->db->select('id, name');
        $cf_names = $this->db->get_where('custom_field_names', array('resource_id' => $resource_id));

        if ($cf_names->num_rows() == 0)
        {
            return false;
        }

        return $cf_names->result_array();
    }

    /**
     * get ID resource 
     * 
     * @param string $resource_name
     * @param boolean $is_main
     * @return int id resource
     */
    public function getResourceID($resource_name = '', $is_main = TRUE)
    {
        $resource_name = ($resource_name) ? $resource_name : $this->router->class;
        
        if ($is_main == TRUE)
        {
            $this->db->select('id');
            $resource = $this->db->get_where('module_resources', array('name' => $resource_name));
        } else 
        {
            $this->db->select('main_id AS id');
            $resource = $this->db->get_where('module_resources', array('name' => $resource_name));
        }
        
        if ($resource->num_rows() == 0)
        {
            return false;
        }
        
        return $resource->row()->id;
    }
    
    /**
     * get Name resource from ID
     * 
     * @param int $resource_id
     * @return string
     */
    public function getResourceName($resource_id)
    {
        $this->db->select('name');
        $this->db->from('module_resources');
        $this->db->where(array('id' => $resource_id));        
        $resource_query = $this->db->get();
        
        if ($resource_query->num_rows() == 0)
        {
            return FALSE;
        }
        
        return $resource_query->row()->name;
    }
    
    /**
     * Get moduleID of resource
     * 
     * @param string $resource_name
     * @return int
     */
    public function getModuleID($resource_name = '')
    {
        $resource_name = ($resource_name) ? $resource_name : $this->router->class;
        $this->db->select('module_id');
        $resource = $this->db->get_where('module_resources', array('name' => $resource_name));
        
        if ($resource->num_rows() == 0)
        {
            return false;
        }
        
        return $resource->row()->module_id;
    }

    /**
     * Pagination
     * 
     * @param int $segment
     * @return array
     */
    public function pagination($segment = 5)
    {                
        $offset = $this->uri->segment($segment);
        
        // get option query
        $options = $this->paginator;
        
        // check offset
        if (!is_numeric($offset))
        {
            $offset = '';
        }
                
        // set limit
        if (!(isset($options['limit']) && $options['limit']))
        {
            $options['limit'] = 20;
        }
        
        // set offset
        $options['offset'] = $offset;                
        
        // get model name
        $model = $this->model_name;
        
        // check exit
        if ($model)
        {
            // load model if load not yet
            if (!class_exists($model))
            {
                $this->load->model($model);
            }
            
            // get result
            $result = $this->$model->find('all', $options);
            
            // get total count            
            $this->count_record = $this->$model->find('count', $options);
            
            return $result;
        }
        
        return array();
    }
    
    /**
     * Get link pagination 
     * 
     * @param string $uri
     * @return string 
     */
    public function getPaginationLink($uri, $segment = 5)
    {
        if (isset($this->paginator['limit']) && $this->paginator['limit'])
        {
            $limit = $this->paginator['limit'];
        } else 
        {
            $limit = 20;
        }
        
        return pagination_config($uri, $this->count_record, $limit, $segment);
    }
    
    /**
     * Delete record from database
     * View on delete list view
     */
    public function deleteRecordOnListView($is_delete = FALSE, $is_restore = FALSE)
    {
        // check permission
        $this->PG_ACL('d');
        
        // get model name
        $model = $this->model_name;
        
        // load model if load not yet
        if (!class_exists($model))
        {
            $this->load->model($model);
        }
        
        // get link redirect to manage page
        $link_redirect = $this->router->fetch_module() . '/' . $this->router->class;
        
        // check post data from form
        if ($this->input->post())
        {
            $list_delete_ids = $this->input->post('listViewId');
            
            if (empty ($list_delete_ids))
            {
                $this->session->set_flashdata('error_message', lang('Error params'));                
                redirect($link_redirect);
            }
            
            foreach ($list_delete_ids as $list_delete_id)
            {
                // if exit field is_delete -> update is_delete = 1
                if ($is_delete == TRUE)
                {
                    // restore recycle bin -> update is_delete = 0
                    if ($is_restore == TRUE)
                    {
                        $this->$model->delete(array('id' => $list_delete_id), TRUE);
                    } else // delete record to recycle bin -> update is_delete = 1
                    {
                        $this->$model->delete(array('id' => $list_delete_id));
                    }
                } else // not exit field is_delete -> delete record
                {
                    $this->$model->deleteRecord(array('id' => $list_delete_id));
                }
            }
            
            $this->session->set_flashdata('success_message', lang('Success'));
            redirect($link_redirect);
        } else 
        {
            $this->session->set_flashdata('error_message', lang('Error params'));
            redirect($link_redirect);
        }
    }
    
    /**
     * DELETE
     * UPDATE record is_delete = 1
     */
    public function deleteOnListView()
    {
        $this->deleteRecordOnListView(TRUE);
    }
    
    /**
     * RESTORE
     * UPDATE record is_delete = 0
     */
    public function restoreOnListView()
    {
        $this->deleteRecordOnListView(TRUE, TRUE);
    }
    
}

?>
